import { MyUpload } from '@/api/index';
import { uploadBaseUrl } from '@/utils/request/request';
import dayjs from 'dayjs';
// 地址解析
import { addressKey } from '@/utils/public';
const QQMapWX = require('@/utils/address-analyze/qqmap-wx-jssdk');
const qqmapsdk = new QQMapWX({
	key: addressKey
});
// 价格截取
export const onPriceCut = (price, index) => {
	// return
	// price.split('.')[index]
	const prices = price.split('.')
	let pricesData = ""
	if (index == 1 && prices.length == 1) pricesData = '00'
	else pricesData = prices[index]
	// console.log('price', prices, price, index)
	return pricesData
}
// 获取顶部高度用于自定义导航
export const getSystemInfo = () => {
	let menuButtonObject = uni.getMenuButtonBoundingClientRect();
	let statusBarHeight = 0;
	let statusBarTop = 0;
	let screenHeight = 0;
	let screenHeightPx = 0;
	uni.getSystemInfo({
		success: (res) => {
			// 导航栏的高度
			const status = menuButtonObject.top + menuButtonObject.height + (menuButtonObject.top - res
				.statusBarHeight);
			// console.log('menuButtonObject',res,menuButtonObject)
			statusBarHeight = (status * 750) / res.screenWidth;
			statusBarTop = (res.statusBarHeight * 750) / res.screenWidth;
			// console.log('statusBarTop',statusBarHeight*750/res.screenWidth)
			screenHeight = res.windowHeight;
			screenHeightPx = menuButtonObject.bottom
		},
		fail: (err) => {
			console.log(err);
		},
	});
	return {
		screenHeightPx,
		statusBarHeight,
		statusBarTop,
		screenHeight
	};
};
// 日期获取
export const datesFuture = (data, format) => {
	return dayjs().add(data, 'day').format(format || 'YYYY-MM-DD')
}
// 获取定位功能
export const getLocation = () => {
	let promise = new Promise(function(resolve, reject) {
		let location = { lat: '', lng: '' }
		let _this = this
		uni.getLocation({
			type: 'wgs84',
			highAccuracyExpireTime: true,
			success: function(res) {
				console.log('res', res)
				uni.setStorageSync('location', { latitude: res.latitude, longitude: res
						.longitude })
				location = {
					lat: res.latitude,
					lng: res.longitude
				}
				resolve(location);
			},
			fail: function(res) {
				console.log('res', res.errMsg)
				if (res.errMsg == 'getLocation:fail auth deny') { // 拒绝地址
					uni.showModal({
						title: '请开启定位',
						content: '请授权开启小程序定位，以便获取附近的小区及优惠',
						confirmText: '开启定位',
						success: function(res) {
							if (res.confirm) {
								uni.openSetting({
									success: function(res) {
										// getLocation()
										// onshow 会重新请求
									}
								})
								console.log('用户点击确定');
							} else if (res.cancel) {
								console.log('用户点击取消');
								uni.setStorageSync('location', { latitude: 0,longitude: 0 })
								resolve(location);
							}
						}
					});
					return
				}
			}
		});
	});
	return promise;
}
// 地址逆解析
export const addressResolution = (latitude, longitude) => {
	let promise = new Promise(function(resolve, reject) {
		qqmapsdk.reverseGeocoder({
			location: {
				latitude: latitude * 1,
				longitude: longitude * 1
			},
			success: function(res) { //成功后的回调
				console.log('成功后的回调', res)
				const address = {
					province: res.result.ad_info.province,
					city: res.result.ad_info.city,
					district: res.result.ad_info.district,
					address: res.result.address_reference.landmark_l2.title
				}
				resolve(address);
			}
		})
	});
	return promise;
}
// 获取当前帐号信息，可以返回小程序的Appid
export const getAccountInfoSync = () => {
	const accountInfo = uni.getAccountInfoSync();
	const miniProgram = {
		appId: accountInfo.miniProgram.appId
	};
	return miniProgram;
};
// 单图上传图片 功能:1-头像,2-商户logo,3-商品,4-环境,5-评论,6-营业执照,7-其他,11-分享
export const singleUpload = (img, type, bool) => {
	let promise = new Promise(function(resolve, reject) {
		if (!bool) {
			uni.showLoading({
				title: '上传中...',
			});
		}
		uni.uploadFile({
			url: `${uploadBaseUrl}${MyUpload}`, //仅为示例，非真实的接口地址
			filePath: img,
			header: {
				Token: uni.getStorageSync('token') || '',
			},
			name: 'file',
			formData: {
				fun: type,
			},
			success: (uploadFileRes) => {
				let allImg = JSON.parse(uploadFileRes.data).data;
				// console.log(allImg);
				resolve(allImg);
			},
			complete(e) {
				// console.log(e)
				if (!bool) uni.hideLoading();
			},
		});
	});
	return promise;
};
// 多传图片
export const MultipassUpload = (img, type, commentImgs) => {
	let promise = new Promise(function(resolve, reject) {
		uni.showLoading({
			title: '上传中...',
		});
		// console.log('imgimgimgimgimgimg', img)
		let allImg = commentImgs || []
		img.map(res => {
			// console.log('res',res.url)
			uni.uploadFile({
				url: `${uploadBaseUrl}${MyUpload}`, //仅为示例，非真实的接口地址
				filePath: res.url,
				header: {
					Token: uni.getStorageSync('token') || 0,
				},
				name: 'file',
				formData: {
					fun: type,
				},
				success: (uploadFileRes) => {
					let img = JSON.parse(uploadFileRes.data).data;
					// console.log('img',img);
					allImg.push({
						url: img.imgURL
					})
					resolve(allImg);
					// console.log('allImg',allImg)
				},
				complete(e) {
					// console.log('complete',e)
					uni.hideLoading();
				},
			});
		})
	});
	return promise;
};
// 距离改变为后两位为km
export const keepDecimal = (data) => {
	let distance = ''
	let datas = data * 1
	const num = datas / 1000
	if (datas > 1000) distance = `${num.toFixed(2)}km`
	else distance = `${String(datas).split('.')[0]}m`
	return distance
};
// 保留小数点后两位 四舍五入
export const roundUp = (data) => {
	let datas = data * 1
	return datas.toFixed(2)
};
// 防抖节流
export const debounce = (func, wait, immediate = true) => {
	let timeout, context, args;
	// 延迟执行函数
	const later = () => setTimeout(() => {
		// 延迟函数执行完毕，清空定时器
		timeout = null
		// 延迟执行的情况下，函数会在延迟函数中执行
		// 使用到之前缓存的参数和上下文
		if (!immediate) {
			func.apply(context, args);
			context = args = null;
		}
	}, wait);
	let debounced = function(...params) {
		if (!timeout) {
			timeout = later();
			if (immediate) {
				//立即执行
				func.apply(this, params);
			} else {
				//闭包
				context = this;
				args = params;
			}
		} else {
			clearTimeout(timeout);
			timeout = later();
		}
	}
	debounced.cancel = function() {
		clearTimeout(timeout);
		timeout = null;
	};
	return debounced;
};
//限制只能输入允许小数的数字  zero | false=不可以输入0 true=可以输入0
export const twoDecimalPlaces = (num, decimal = 2, zero, limit) => {
	// console.log('str',num)
	let str = num.toString().replace(/[^0-9\.]*/g, '');
	let temp = str.slice(0, 1)
	while (!/^[0-9]*$/.test(temp) && str.length) {
		str = str.slice(1)
		temp = str.slice(0, 1)
	}
	// if(str)
	if (str == 0 && !zero) return ''
	if (str == '00') return '0'
	if (str == '..') return '.'
	if (str >= limit && limit) return str.slice(0, (limit + '').length)
	// else if (str > limit && limit == 20000) return str <= 20000 ? str.slice(0, 5) : str.slice(0, 4)
	if (str.includes('.')) {
		const arr = str.split('.')
		const length = arr[1].length
		if (length >= decimal) {
			const str1 = arr[0] + '.' + arr[1].slice(0, decimal);
			return decimal === 0 ? String(arr[0]) : String(str1)
		} else {
			return String(arr[0] + '.' + arr[1])
		}
	} else {
		// console.log('length1', length)
		console.log('decimal1', decimal)
		return String(str)
	}
}
// 用户缓存数据
export const infoDataCache = (data) => {
	const setData = {
		name: data.userName,
		mobile: data.mobileNumber,
		balanceAmt: data.balanceAmt,
		userId: data.userId,
		isUserCardId: data.isUserCardId
	} // 信息存在缓存里面
	return setData
}
// 计算销量
// export const calculate = (sales,sales1) => {
// 	console.log('sales',sales,sales1)
// 	let salesNum = sales1*1 - sales*1
// 	console.log('salesNum',salesNum)
// }
// 用户隐私协议
// export const getPrivacySetting = () => {
// 	let promise = new Promise(function(resolve, reject) {
// 		uni.getPrivacySetting({
// 			success: res => {
// 				if (res.needAuthorization) {
// 					resolve(res);
// 				} else {
// 				}
// 			},
// 			fail: () => {},
// 			complete: () => {}
// 		})

// 	});
// 	// return promise;
// };